package server;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.xml.sax.SAXException;
import server.catalina.core.Connector;
import server.catalina.core.Host;
import server.catalina.core.LagouClassLoader;
import server.catalina.core.Mapper;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.*;
import java.util.concurrent.*;

/**
 * Minicat的主类
 */
public class Bootstrap {

    /**
     * 定义socket监听的端口号
     */
    private int port = 8080;

    private Map<String, HttpServlet> servletMap = new HashMap<>();

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    /**
     * Minicat启动需要初始化展开的一些操作
     */
    public void start() {
        // 加载解析相关的配置，web.xml
        Mapper mapper = init();

        // 定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize = 50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );

        /**
         * MinicatV4.0
         * @return
         */
        try {
            int port = mapper.getConnector().getPort();
            ServerSocket serverSocket = new ServerSocket(port);
            System.out.println("=====>>Minicat start on port: " + port);
            while (true) {
                Socket socket = null;
                try {
                    socket = serverSocket.accept();
                    RequestProcessor requestProcessor = new RequestProcessor(socket, mapper.getMappedContextMap());
                    threadPoolExecutor.execute(requestProcessor);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private Mapper init() {
        // 解析server.xml
        Mapper mapper = new Mapper();

        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("conf/server.xml");
        SAXReader saxReader = new SAXReader();
        try {
            saxReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();
            Element connectorEle = ((Element) rootElement.selectSingleNode("//Connector"));
            String port = connectorEle.attributeValue("port");
            Element hostElement = ((Element) rootElement.selectSingleNode("//Host"));
            String name = hostElement.attributeValue("name");
            String appBase = hostElement.attributeValue("appBase");
            Connector connector = new Connector(Integer.parseInt(port));
            mapper.setConnector(connector);
            mapper.setHost(new Host(name, appBase));
            // 遍历appBase
            File dir = new File(appBase);
            File[] files = dir.listFiles();
            for (File file : files) {
                if (file.isDirectory()) {
                    String contextPath = file.getName();
                    String appPath = appBase + File.separatorChar + contextPath;
                    File[] webXmlFile = file.listFiles(new FilenameFilter() {
                        @Override
                        public boolean accept(File dir, String name) {
                            return "web.xml".equals(name);
                        }
                    });
                    Map<String, HttpServlet> httpServletMap = loadServlet(new FileInputStream(webXmlFile[0]), appPath);
                    List<Wrapper> wrappers = new ArrayList<>(10);
                    httpServletMap.forEach((key, value) -> {
                        Wrapper wrapper = new Wrapper();
                        wrapper.setServlet(value);
                        wrappers.add(wrapper);
                    });
                    Map<String, List<Wrapper>> mappedContextMap = mapper.getMappedContextMap();
                    mappedContextMap.put(contextPath, wrappers);
                }
            }
        } catch (DocumentException | FileNotFoundException | SAXException e) {
            e.printStackTrace();
        }
        return mapper;
    }

    private static File[] listDirectory(File dir) {
        File[] files = dir.listFiles();
        if (files == null) {
            return new File[0];
        }
        Arrays.sort(files, Comparator.comparing(File::getName));
        return files;
    }

    private Map<String, HttpServlet> loadServlet(InputStream resourceAsStream, String appPath) throws SAXException {
        LagouClassLoader lagouClassLoader = new LagouClassLoader(appPath);
        Map<String, HttpServlet> servletMap = new HashMap<>();
        SAXReader saxReader = new SAXReader();
        saxReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();
            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (Element selectNode : selectNodes) {
                Element element = selectNode;
                Element servletNameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletNameElement.getStringValue();
                Element servletClassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletClassElement.getStringValue();

                // /web-app/servlet-mapping[servlet-name=']?']
                String s = "/web-app/servlet-mapping[servlet-name='" + servletName + "']";
                // 根据servlet-name的值找到url-pattern
                Node servletMapping = rootElement.selectSingleNode(s);
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                Object ins = lagouClassLoader.loadClass(servletClass).newInstance();
                servletMap.put(urlPattern, (HttpServlet) ins);
            }

        } catch (DocumentException | ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
        return servletMap;
    }

    public static void main(String[] args) {

        new Bootstrap().start();

    }
}
